<?php
namespace app\jiaxiaotong\controller;

use app\classes\model\ClassModel;
use app\classes\model\ClassSeatModel;
use app\course\model\CourseModel;
use app\course\model\CourseScheduleModel;
use app\educational\model\MessageModel;
use app\financial\model\AwardCardModel;
use app\financial\model\DiscountModel;
use app\financial\model\HelpAwardModel;
use app\financial\model\HelpAwardMoneyModel;
use app\financial\model\OrderModel;
use app\order\service\OrderService;
use app\order\validate\HelpAwardValidate;
use app\student\model\StudentModel;
use app\system\model\SchoolModel;
use app\educational\model\TeacherHomeworkModel;
use app\educational\model\StudentScoreModel;
use cmf\controller\HomeBaseController;
use think\Db;
use think\Exception;


class JiaXiaoTongController extends CommonController
{

    public function index()
    {
        $this->student();
        return $this->fetch();
    }

    /*
     * 申请助学金
     */
    public function helpAward()
    {
        $student_id = $this->student();
        $this->assign('student_id', $student_id);
        //加入孩子已经审批过了，请等待
        $help_award_model = new HelpAwardModel();
        $count = $help_award_model->alias('ha')
            ->field('ha.*,help_award_money.price')
            ->where(['student_id' => $student_id])
            ->join('help_award_money','help_award_money.type=ha.type')
            ->select();
        if(!$count->isEmpty())
        {
            $count=$count->toArray();
                foreach($count as $k=>$v)
                {
                    if ($v['type'] == 1) {
                        $count[$k]['type'] = '重大疾病';
                    } else if ($v['type'] == 2) {
                        $count[$k]['type'] = '单亲';
                    }else{
                        $count[$k]['type'] = '其他';
                    }
                }
        }

        //查询助学金金额;

        $this->assign('count', $count);
        return $this->fetch();
    }

    /*
     * helpAwardPost 助学金的添加
     */
    public function helpAwardPost()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if(empty($post['type']))
            {
                $this->error('请选择助学金类型');
            }
            $student_id = $post['student_id'];
            if (empty($_SESSION['student_id'])) {
                $student_id = parent::first_student();
            } else {
                $student_id = $_SESSION['student_id'];
            }

            //资源表
            $asset = Db::name('asset');
            $help_award_model = new HelpAwardModel();

            if (!isset($_FILES['doc']['name']) && empty($_FILES['doc']['name'])) {
                $this->error('亲,上传文件或者图片');
            };

            $type = pathinfo($_FILES['doc']['name'], PATHINFO_EXTENSION);

            $allow_type = ['doc', 'docx','png','jpg','jpeg','gif'];
            if (!in_array(strtolower($type), $allow_type)) {
                $this->error('上传不是word文件或者图片');
            }
            if($_FILES['doc']['size']/1024/1024>1)
            {
                $this->error('上传文件过大');
            }

            $filereturn = $this->upload('doc', $dir = './upload/helpawrd/');
            $dir = substr($filereturn, 0, 8);
            $filepath = ('helpawrd/' . $dir . '/' . $filereturn);
            $result = $this->validate($post, 'HelpAward');
            if ($result !== true) {
                $this->error($result);
            }
//            //加入孩子已经审批过了，请等待
//            $count = $help_award_model->where(['student_id' => $student_id])->count("*");
//            if ($count > 0) {
//                $this->error('助学金已经申请过了');
//            }
            $allow_type_doc = ['doc', 'docx','png','jpg','jpeg','gif'];
            $allow_type_img = ['png','jpg','jpeg','gif'];
            Db::startTrans();
            try {

                //doc 的表 asset
                $doc = $_FILES['doc'];
                $asset_data = [];
                $data = [];
                $asset_data['create_time'] = time();
                $asset_data['filename'] = $doc['name'];
                $asset_data['file_path'] = $filepath;
                $asset_data['suffix'] = $type;
                $asset_id = $asset->insertGetId($asset_data);
                //如果

                $help_award_model_data=$help_award_model->where(['student_id'=>$student_id])->select();
                if(!$help_award_model_data->isEmpty())
                {
                    $help_award_model_data=$help_award_model_data->toArray();
                    foreach($help_award_model_data as $k=>$v)
                    {
                        if($v['type']==$post['type'])
                        {
                            $this->error('你已经申请过此类助学金了');
                        }
                    }
                   $money=Db::name('help_award_money')->where(['id'=>$post['type']])->value('price');
                    $data['asset_id'] = $asset_id;
                    $data['award_id'] = $post['type'];
                    $data['student_id'] = $student_id;
                    $data['content'] = $post['content'];
                    $data['type'] = $post['type'];
                    $data['create_time'] = time();
                    $data['money'] = $money;
                    $help_award_model->insert($data);
                }else{
                    //助学金表
                    $money=Db::name('help_award_money')->where(['id'=>$post['type']])->value('price');
                    $data['asset_id'] = $asset_id;
                    $data['award_id'] = $post['type'];
                    $data['student_id'] = $student_id;
                    $data['content'] = $post['content'];
                    $data['type'] = $post['type'];
                    $data['create_time'] = time();
                    $data['money'] = $money;
                    $help_award_model->insert($data);
                }



                Db::commit();
                $this->success('助学金申请成功，等待审核');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('助学金申请失败');
            }


        }
    }

    /*
     * 上传的函数
     */
    function upload($name, $dir = './upload/', $allow_type = array('doc', 'docx', 'jpg','jpeg','png','gif'))
    {

        if ($_FILES[$name]['error'] > 0) {
            echo '上传错误';
            return false;
        }
        //2.获取后缀名
        $type = pathinfo($_FILES[$name]['name'], PATHINFO_EXTENSION);
        //  echo $type;
        if (!in_array($type, $allow_type)) {
            echo '上传一个execel过来';
            return false;
        }
        //3.起名字
        $filename = date('Ymd') . uniqid() . mt_rand(0, 9999) . '.' . $type;

        //4.保存路径

        $save_path = rtrim($dir, '/');
        $save_path .= '/';
        $save_path .= date('Ymd');
        // echo $save_path;
        if (!file_exists($save_path)) {
            mkdir($save_path, '0777', true);
            chmod($save_path, '0755');
        }
        $path = $save_path . '/' . $filename;

        if (!is_uploaded_file($_FILES[$name]['tmp_name'])) {
            return false;
        }
        if (!move_uploaded_file($_FILES[$name]['tmp_name'], $path)) {
            return false;
        }

        return $filename;

    }

    /*
     * 孩子课程情况
     */
    public function seeCourse()
    {
        $student_id = $this->student();
        $this->assign('student_id', $student_id);
        $student_model = new StudentModel();
        //chase添加用于查询全部学生
        $student_data = $student_model->where('id', $student_id)->find();
        $class_model = new ClassModel();

        //没有去处重复->distinct('ct.*')
        $count = $class_model->alias('c')
            ->field('c.name name,c.class_start_week,c.continue_class_content,c.class_time_start,c.class_time_end,c.id,c.class_status,c.current_num,
            c.total_num,
            sc.name school,ct.delete_time ctdelete_time,
            o.student_id,o.order_status,cs.name as classroom_name,o.continue_year_type,ct.student_id ctstudent_id,
            cs.student_nums,u.user_login as user_login,co.course_name,co.course_hour')
            ->join('school sc', 'c.school_id=sc.id')
            ->join('class_student ct','ct.class_id=c.id')
            ->join('classroom cs', 'c.classroom_id=cs.id')
            ->join('course co', 'c.course_id=co.id')
            ->join('asset as','as.id=co.record_asset_id',$type='left')
            ->join('user u', 'c.teacher_id=u.id')
            ->join('order o', 'o.class_id=c.id and o.class_id=ct.class_id and o.student_id=ct.student_id',$type='left')
            ->where(['ct.student_id'=>$student_id])
            ->select()->toArray();


        //删除没有付钱班级
        foreach($count as $k=>$v)
        {
            if(!is_null($v['order_status']))
            {

                if($v['order_status']==0 ||  $v['order_status']==3)
                {
                    //如果连报，删除没有支付订单和 连报
                    if($v['continue_year_type']==2)
                    {
                            $continue_id=$this->enable_class($v['id'])[0];

//                            $continue_class=Db::name('order')->where(['student_id'=>$student_id,'class_id'=>$continue_id])->find();
                           foreach($count as $j=>$val)
                           {


                               if($val['id']==$continue_id && $val['ctstudent_id']==$student_id)
                               {
                                     unset($count[$j]);
                               }
                           }

                    }
                    if($v['continue_year_type']==3)
                    {
                        $continue_id=$this->enable_class($v['id'])[0];
                        $continue_id1=$this->enable_class($v['id'])[1];

//                            $continue_class=Db::name('order')->where(['student_id'=>$student_id,'class_id'=>$continue_id])->find();
                        foreach($count as $j=>$val)
                        {
                            if($val['id']==$continue_id && $val['ctstudent_id']==$student_id)
                            {
                                unset($count[$j]);
                            }
                            if($val['id']==$continue_id1 && $val['ctstudent_id']==$student_id)
                            {
                                unset($count[$j]);
                            }
                        }
                    }
                    unset($count[$k]);
                }
                if($v['order_status']!=4 && $v['ctdelete_time'] != 0)
                {
                    unset($count[$k]);

                }

            }



        }
        $count=count($count);


        $data = $class_model->alias('c')
            ->field('c.name name,c.class_start_week,c.continue_class_content,c.class_time_start,c.class_time_end,c.id,c.class_status,c.current_num,
            c.total_num,
            sc.name school,ct.delete_time ctdelete_time,
            o.student_id,o.order_status,cs.name as classroom_name,o.continue_year_type,ct.student_id ctstudent_id,
            cs.student_nums,u.user_login as user_login,co.course_name,co.course_hour,as.filename,as.id asid')
            ->join('school sc', 'c.school_id=sc.id')
            ->join('class_student ct','ct.class_id=c.id')
            ->join('classroom cs', 'c.classroom_id=cs.id ')
            ->join('course co', 'c.course_id=co.id ')
            ->join('asset as','as.id=co.record_asset_id',$type='left')
            ->join('user u', 'c.teacher_id=u.id')
            ->join('order o', 'o.class_id=c.id and o.class_id=ct.class_id and o.student_id=ct.student_id',$type='left')
            ->where(['ct.student_id'=>$student_id])
//            ->select()->toArray();
            ->order('c.start_lesson_time', 'desc');


//        dump($data);
        $data=$data->paginate(4,$total=$count);

        //删除没有付钱班级
        foreach($data as $k=>$v)
        {
            if(!is_null($v['order_status']))
            {
                if($v['order_status']==0 || $v['order_status']==3)
                {
                    //如果连报，删除没有支付订单和1年连报
                    if($v['continue_year_type']==2)
                    {
                        $continue_id=$this->enable_class($v['id'])[0];

//                            $continue_class=Db::name('order')->where(['student_id'=>$student_id,'class_id'=>$continue_id])->find();
                        foreach($data as $j=>$val)
                        {


                            if($val['id']==$continue_id && $val['ctstudent_id']==$student_id)
                            {
                                unset($data[$j]);
                            }
                        }

                    }
                    if($v['continue_year_type']==3)
                    {
                        $continue_id=$this->enable_class($v['id'])[0];
                        $continue_id1=$this->enable_class($v['id'])[1];

//                            $continue_class=Db::name('order')->where(['student_id'=>$student_id,'class_id'=>$continue_id])->find();
                        foreach($data as $j=>$val)
                        {
                            if($val['id']==$continue_id && $val['ctstudent_id']==$student_id)
                            {
                                unset($data[$j]);
                            }
                            if($val['id']==$continue_id1 && $val['ctstudent_id']==$student_id)
                            {
                                unset($data[$j]);
                            }
                        }
                    }
                    unset($data[$k]);

                }
                if($v['order_status']!=4 && $v['ctdelete_time'] != 0)
                {
                    unset($data[$k]);

                }
            }
            //去除重复


        }
//        //并班的学生重新占座
        $res=Db::name("class_student")->alias('cs')->field('c.name cname,cs.class_id,cs.pre_class_ids')
            ->join('class c','c.id=cs.class_id')
            ->where(['cs.student_id'=>$student_id,'status'=>1])
            ->select();

        $xu_class=0; //续班的按钮

        //课程的进度
        foreach ($data as $k => $v) {
            $class_data = Db::name('class')->where(['id' => $v['id']])->find();
            $is_class = $class_data['is_class'];
            $enable_class = $class_data['enable_class_ids'];
            if (!empty($is_class))
            {
                if (!empty($enable_class))
                {
                    $class_id_xu = intval(explode(',', $enable_class)[0]);
                    $status=Db::name('class')->where(['id'=>$class_id_xu,'class_status'=>0])->find(); //没有续班的
                    if(!empty($status))
                    {
                        $xu_class=0;
                    }
                    $xu_class=Db::name('order') //在订单中找到了，但是连报找不到订单，只有
                    ->where(['class_id'=>$class_id_xu,'student_id'=>$student_id])
                        ->where('order_status',['eq', 2], ['eq', 1], ['eq', 4],'or')
                        ->find();

                    if(!empty($xu_class))
                    {
                        $xu_class=1;
                    }


                    //连报的从class_student
                    $xu_class_lian=Db::name('class_student') //在订单中找到了，但是连报找不到订单，只有
                    ->where(['class_id'=>$class_id_xu,'student_id'=>$student_id])
                        ->where('delete_time',0)
                        ->find();
                    if(!empty($xu_class_lian))
                    {
                        $xu_class=1;
                    }
                    $data[$k]['xu_class']=$xu_class;
                }else{
                    $data[$k]['xu_class']=0;
                }
            }
            $class_start_week = explode(',', $v['class_start_week']);
            $class_time_start = explode(',', $v['class_time_start']);
            $class_time_end = explode(',', $v['class_time_end']);
            $data[$k]['class_start_week'] = '';
            foreach ($class_start_week as $j => $val) {
                if (substr($class_time_start[$j], 1) >= 1) { //时间统一显示
                    $ww = '上午';
                } else {
                    $ww = '下午';
                }
                $data[$k]['class_start_week'] .= " 周" . $class_start_week[$j] . $ww . $class_time_start[$j] . "-" . $class_time_end[$j];
                //续班续了，就不能


            }
            $where = [
                'class_id' => ['=', $v['id']],
            ];
            //选座位
            if(count($res)>0)
            {
                //chase添加查询座位信息;
                //$cid应为传输过来的班级id;
                //查询班级对应教室,家长座位,过道,排列;
                $class_student=Db::name('class_student')->where(['old_class_id'=>$v['id'],'status'=>1])->find();
                if(!is_null($class_student))
                {
                    $data[$k]['class_id']=$class_student['class_id'];
                    $data[$k]['old_class_id']=$class_student['old_class_id'];
                    $data[$k]['pre_class_ids']=$class_student['pre_class_ids'];
                    $data[$k]['status']=$class_student['status'];
                }

                if(!empty($class_student))
                {
                    $seat_data = $class_model->alias('c')->where('c.id', $class_student['class_id'])
                        ->field('c.classroom_id,cr.rows,cr.cols,cr.aisle,cr.vip,cr.student_nums')
                        ->join('classroom cr', 'cr.id=c.classroom_id')
                        ->select()
                        ->toArray();
                    if (!empty($seat_data[0]['aisle'])) {
                        $seat_data[0]['aisle'] = unserialize($seat_data[0]['aisle']);
                    }
                    if (!empty($seat_data[0]['vip'])) {
                        $seat_data[0]['vip'] = unserialize($seat_data[0]['vip']);
                    }
                    $seat_data[0]['student_seat'] = '';

                    //查询班级中保留座位和学生已选座位
                    $class_seat_model = new ClassSeatModel();
                    $class_seat_data = $class_seat_model->alias('cs')
                        ->field('cs.student_seat,cs.reserved_seats')
                        ->where('classes_id', $v['id'])
                        ->where('delete_time',0)
                        ->select()
                        ->toArray();
                    foreach ($class_seat_data as &$x) {
                        if (!empty($x['student_seat'])) {
                            $seat_data[0]['student_seat'] = $seat_data[0]['student_seat'] . unserialize($x['student_seat']) . ",";
                        }
                        if (!empty($x['reserved_seats'])) {
                            $seat_data[0]['reserved_seats'] = unserialize($x['reserved_seats']);
                        }
                    }
                    if (empty($seat_data[0]['student_seat'])) {
                        $seat_data[0]['student_seat'] = '';
                    }
                    if (empty($seat_data[0]['reserved_seats'])) {
                        $seat_data[0]['reserved_seats'] = '';
                    }
                }
            }

            $date = Db::name('course_schedule')->where($where)->order('date', 'asc')->select();
            if ($date->isEmpty()) { //课时为空的情况
                $this->error('课时情况正在调整');
            }
            $len = count($date);

            if (!$date->isEmpty()) {
                 $date=$date->toArray();
                $first_day = date("Y.m.d", $date[0]['date']);
                $end_day = date("Y.m.d", $date[$len - 1]['date']);
                $data[$k]['first_day'] = $first_day;
                $data[$k]['end_day'] = $end_day;
                $cur_time = time();
                foreach ($date as $kk => $val) {
                    if ($cur_time < $date[0]['date']) {
                        $data[$k]['schedule'] = 0;
                    } else if ($cur_time >= $date[$kk]['date']) {
                        $data[$k]['schedule'] = $date[$kk]['schedule'];
                    }
                }
            } else {
                $data[$k]['schedule'] = 0;
                $data[$k]['first_day'] = '暂无排课';
                $data[$k]['end_day'] = '暂无排课';
            }
            //能否续班
            $data[$k]['xu'] = $this->enable_class($v['id']);
        }



        $this->assign('data', $data);


        $this->assign('student_data', $student_data);
        $this->assign('page', $data->render());
        $this->assign('student_id', $student_id);

        //chase添加查询座位信息end;

        return $this->fetch();
    }

    /*
 * 递归一个函数连报,首先判断连报的课程的 is_class enable_class_ids
 */
    public function enable_class($class_id, $data = [])
    {
        $class_data = Db::name('class')->where(['id' => $class_id])->find();
        $is_class = $class_data['is_class'];
        $enable_class = $class_data['enable_class_ids'];
        if (!empty($is_class)) {
            if (!empty($enable_class)) {
                $class_id = intval(explode(',', $enable_class)[0]);
                $data[] = $class_id;
                $data = array_merge($data, $this->enable_class($class_id));
            }
        }else{
            $data=[];
        }
        return $data;
    }

    /*
     * 班级课时详情
     */
    public function course_shecma_views()
    {
        $student_id = $this->student();
        $this->assign('student_id', $student_id);

        $class_id = $this->request->param('id', '0');
        $course_schema = new CourseScheduleModel();
        $data = $course_schema->where(['class_id' => $class_id])->select();
        $time = time();

        if (!empty($data)) {
            foreach ($data as &$v) {
                if ($v['date'] > $time) {
                    $v['status'] = 1;
                } else {
                    $v['status'] = 0;
                }
            }
        }

        //chase添加查询座位信息;
        //$cid应为传输过来的班级id;
        $cid = $class_id;
        //查询班级对应教室,家长座位,过道,排列;
        $class_model = new ClassModel();
        $seat_data = $class_model->alias('c')->where('c.id', $cid)
            ->field('c.classroom_id,cr.rows,cr.cols,cr.aisle,cr.vip,cr.student_nums')
            ->join('classroom cr', 'cr.id=c.classroom_id')
            ->select()
            ->toArray();
        if (!empty($seat_data[0]['aisle'])) {
            $seat_data[0]['aisle'] = unserialize($seat_data[0]['aisle']);
        }
        if (!empty($seat_data[0]['vip'])) {
            $seat_data[0]['vip'] = unserialize($seat_data[0]['vip']);
        }
        $seat_data[0]['student_seat'] = '';
        $seat_data[0]['this_student_seat'] = '';

        //查询班级中保留座位和学生已选座位
        $class_seat_model = new ClassSeatModel();
        $class_seat_data = $class_seat_model->alias('cs')
            ->field('cs.student_seat,cs.reserved_seats,cs.student_id')
            ->where('classes_id', $cid)
            ->where('delete_time',0)
            ->select()
            ->toArray();
        foreach ($class_seat_data as &$x) {
            if (!empty($x['student_seat'])) {
                if ($x['student_id'] == $student_id) {
                    $seat_data[0]['this_student_seat'] = unserialize($x['student_seat']);
                } else {
                    $seat_data[0]['student_seat'] = $seat_data[0]['student_seat'] . unserialize($x['student_seat']) . ",";
                }
            }
            if (!empty($x['reserved_seats'])) {
                $seat_data[0]['reserved_seats'] = unserialize($x['reserved_seats']);
            }
        }

        if (empty($seat_data[0]['student_seat'])) {
            $seat_data[0]['student_seat'] = '';
        }
        if (empty($seat_data[0]['reserved_seats'])) {
            $seat_data[0]['reserved_seats'] = '';
        }
        $this->assign('seat_data', $seat_data);
        //chase添加查询座位信息end;

        $this->assign('data', $data);
//        $this->assign('student_id', $student_id);
        return $this->fetch();
    }

    /*
     * 续班的需求
     */
    public function continue_class()
    {
        $student_id = $this->request->param('student_id', '0');
        $class_id = $this->request->param('id', '0');

        /*
         * 每个controller东东
         */

        //选择孩子情况
        $student_id = $this->student();

        if (empty($student_id)) {
            return $this->redirect('order/order/add_student');
        }

        //当前用户的id
        $p_id = cmf_get_current_user_id();
        //当前的用户去登录
        if (empty($p_id)) {
            $this->redirect('user/login/index');
        }
        //如果连续生成两次订单，生成第三次的时候先去支付或者取消订单
        $order_model = new OrderModel();
        $order_count = $order_model->where(['parent_id' => $p_id, 'order_status' => 0])->count();
        if ($order_count > 1) {
            $this->error('你还有没有支付的订单呢');
        }


        //优惠活动
        $discount = new DiscountModel();
        $discount_data = $discount->where(['delete_time' => 0])->select()->toArray();


        //班级详情
        $class_model = new ClassModel();
        $course_model = new CourseModel();
        $is_continue_class = explode(',', $class_model->where(['id' => $class_id])->value('enable_class_ids'))[0];
        $data = $class_model
            ->where(['id' => $is_continue_class])
            ->find();
        if ($data['total_num'] <= $data['current_num']) {
            $this->error('此班级已经满员了');
        }
        //判断这个班级和这个课程是否能够连报二年，最多就是三年
        $enable_class = $this->enable_class($is_continue_class);
        $student_model = new StudentModel();
        $student_name = $student_model->where('id', $student_id)->value('name');
        //上课的时间
        //凭借多个上课时间段
        $class_start_week = explode(',', $data['class_start_week']);
        $class_time_start = explode(',', $data['class_time_start']);
        $class_time_end = explode(',', $data['class_time_end']);
        $data['class_start_week'] = '';

        foreach ($class_start_week as $j => $v) {
            if ($class_time_start[$j] <= 13) {
                $ww = '上午';
            } else {
                $ww = '下午';
            }

            switch ($class_start_week[$j]) {
                case 6:
                    $class_week = '星期六';
                    break;
                case 7:
                    $class_week = '星期日';
                    break;
                case 5:
                    $class_week = '星期五';
                    break;
                case 4:
                    $class_week = '星期四';
                    break;
                case 3:
                    $class_week = '星期三';
                    break;
                case 2:
                    $class_week = '星期二';
                    break;
                default:
                    $class_week = '星期一';
            }
            $data['class_start_week'] .= $class_week . $ww . $class_time_start[$j] . "-" . $class_time_end[$j] ."  ";

        }
        //续班的id
        //查看课时
        $lesson_schema = Db::name('course_schedule')->where(['class_id' => $is_continue_class])->order('date', 'asc')->select();
        if (is_null($lesson_schema)) {
            $this->error('课时情况正在调整');
        }
        $lesson_schema = $lesson_schema->toArray();
        sort($lesson_schema);
        $len = count($lesson_schema);

        if (empty($lesson_schema)) {
            $this->error('家校通续班的错误');
        }

        $class_status = $class_model->where(['id' => $class_id])->value('class_status'); //获取班级的id
        if ($class_status == 3) {
            $this->error('班级已经结课了');
        }
        if (isset($_SESSION['student_status1']) && !empty($_SESSION['student_status1'])) {
            unset($_SESSION['student_status1']);
        }
        $_SESSION['student_status1'] = 4;
        if (isset($_SESSION['class_id']) && !empty($_SESSION['class_id'])) {
            unset($_SESSION['class_id']);
        }
        $_SESSION['class_id'] = $class_id;

        $course_id = $class_model->where('id', $class_id)->value('course_id');
        $length = $course_model->where('id', $course_id)->value('course_hour');
        $course_data = $course_model->where('id', $course_id)->find();

        if (!isset($course_data['one_reduce_price'])) {
            $course_data['one_reduce_price'] = 0;
        }
        if (!isset($course_data['two_reduce_price'])) {
            $course_data['one_reduce_price'] = 0;
        }
        if (!isset($course_data['three_reduce_price'])) {
            $course_data['one_reduce_price'] = 0;
        }
        //奖学金/牛牛卡
        $award_card = new AwardCardModel();
        $award_order_id = Db::name('award_order')->column('award_student_id');

        $student_id = $this->request->param('student_id');
        $award_card_data = $award_card->alias('d')
            ->join('award_student aw', 'aw.award_id=d.id')
            ->where(['d.delete_time' => 0, 'aw.student_id' => $student_id])
            ->where('aw.award_id', 'not in', $award_order_id)
//            ->buildSql();
            ->select()->toArray();
        $help_awrad = new HelpAwardModel();
        //助学的判断是否有而且通过审核
        $help_awrad_data = $help_awrad->alias('ha')
            ->join('help_award_money h', 'ha.award_id=h.id')
            ->where(['ha.student_id' => $student_id, 'ha.status' => 2])->value('h.price');

        //chase添加查询座位信息;
        //$cid应为传输过来的班级id;
        //查询班级对应教室,家长座位,过道,排列;
        $seat_data = $class_model->alias('c')->where('c.id', $class_id)
            ->field('c.classroom_id,cr.rows,cr.cols,cr.aisle,cr.vip,cr.student_nums')
            ->join('classroom cr', 'cr.id=c.classroom_id')
            ->select()
            ->toArray();
        if (!empty($seat_data[0]['aisle'])) {
            $seat_data[0]['aisle'] = unserialize($seat_data[0]['aisle']);
        }
        if (!empty($seat_data[0]['vip'])) {
            $seat_data[0]['vip'] = unserialize($seat_data[0]['vip']);
        }
        $seat_data[0]['student_seat'] = '';

        //查询班级中保留座位和学生已选座位
        $class_seat_model = new ClassSeatModel();
        $class_seat_data = $class_seat_model->alias('cs')
            ->field('cs.student_seat,cs.reserved_seats')
            ->where('classes_id', $class_id)
            ->where('delete_time',0)
            ->select()
            ->toArray();

        foreach ($class_seat_data as &$x) {
            if (!empty($x['student_seat'])) {
                $seat_data[0]['student_seat'] = $seat_data[0]['student_seat'] . unserialize($x['student_seat']) . ",";
            }
            if (!empty($x['reserved_seats'])) {
                $seat_data[0]['reserved_seats'] = unserialize($x['reserved_seats']);
            }
        }

        if (empty($seat_data[0]['student_seat'])) {
            $seat_data[0]['student_seat'] = '';
        }
        if (empty($seat_data[0]['reserved_seats'])) {
            $seat_data[0]['reserved_seats'] = '';
        }


        $this->assign('seat_data', $seat_data);
        //chase添加查询座位信息end;


        $this->assign('class_status', $class_status);
        $this->assign('data', $data);
        $this->assign('course_data', $course_data);
        $this->assign('enable_class', $enable_class);
        $this->assign('student_id', $student_id);
        $this->assign('student_name', $student_name);
        $this->assign('award_card_data', $award_card_data);
        $this->assign('help_awrad_data', $help_awrad_data);


        return $this->fetch();
    }

    /*
        * 续班的订单
        */
    public function product_order()
    {


        if ($this->request->isPost()) {
            $post = $this->request->post();
            $class_id = $post['class_id'];       //班级id
            $student_id = $post['student_id'];
            $cha_id = $this->request->param('cha_id', '0');     //是否插板
            $post['cha_id'] = $cha_id;
            //判断学生是否在此班级占座了
            $class_seat_model = new ClassSeatModel();
            $student_seat = $class_seat_model->where(['classes_id' => $class_id, 'student_id' => $student_id, 'delete_time' => 0])->find();
            if (!empty($student_seat)) {
                $this->error('您在此班级已经报过名了!!!');
            }
            if (empty($student_id)) {
                //选择学生为空
                $this->error('请选择孩子');
            }
            if (empty($post['student_seat'])) {
                $this->error('请至少选择一个座位');
            }

            //注意并发性
            $file = fopen(__DIR__ . '/2.html.lock', "w+");

            // 排它性的锁定
            if (flock($file, LOCK_EX)) {
                fwrite($file, "Write something");
                $count = $class_seat_model->where(['classes_id' => $class_id, 'student_seat' => $student_seat])->find();

                if (!is_null($count)) {
                    flock($file, LOCK_UN);
                    $this->error('座位已经占了');
                }
                // release lock
                flock($file, LOCK_UN);
            } else {
                echo "Error locking file!";
            }
            $orderService = new OrderService();
            $code = $orderService->product_order($post);
            $order_id = Db::name('order')->where('id', $code)->value('order_id');
            if ($order_id) {
                $this->success('选座成功', url('order/FrontOrder/orderPay', array('order_id' => base64_encode($order_id), 'student_id' => $student_id)));
            } else {
                $this->error('选座失败');
            }

        }
    }

    /*
     * 孩子课程情况
     */
    public function seehomework()
    {
        $student_id=$this->student();

        $class_id=$this->request->param('id');
        $tui=$this->request->param('tui',0);


        $homeword_model = new TeacherHomeworkModel();

        if(!empty($tui))
        {
            $delete_time=Db::name('class_student')->where(['class_id'=>$class_id,'student_id'=>$student_id,'is_refuse'=>2])->value('delete_time'); //也就退课会软删除
            $data = $homeword_model->alias('hw')->distinct('hw.*') //去重复
                ->field('hw.*,cs.class_id,cl.name classname,us.user_login teachername')
                ->join('class_student cs', 'cs.class_id=hw.class_id')
                ->join('class cl', 'cl.id=hw.class_id')
                ->join('user us', 'us.id=hw.teacher_id')
                ->where('hw.create_time','lt',$delete_time)
                ->where(['hw.class_id' => $class_id])
                ->order('hw.create_time', 'desc')
//                ->select()->toArray();
                ->paginate(5);
//            dump($data);
//            dump($delete_time);
        }else{

            $data = $homeword_model->alias('hw')->distinct('hw.*') //去重复
                ->field('hw.*,cs.class_id,cl.name classname,us.user_login teachername')
                ->join('class_student cs', 'cs.class_id=hw.class_id')
                ->join('class cl', 'cl.id=hw.class_id')
                ->join('user us', 'us.id=hw.teacher_id')
                ->where(['hw.class_id' => $class_id])
                ->order('hw.create_time', 'desc')
                ->paginate(5);
        }


        $this->assign('student_id',$student_id);
        $this->assign('data', $data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /*
    * 孩子成绩
    */
    public function viewscore()
    {
        $limit = config('limit_front_per_page');
        $student_id = $this->student();

        $score_model = new StudentScoreModel();
        $data = $score_model->alias('sc')
            ->field('sc.*,cl.name classname')
            ->join('class cl', 'cl.id=sc.class_id')
            ->where(['sc.shop_id' => $this->front_shop_id])
            ->where(['sc.delete_time' => 0])
            ->where(['sc.student_id' => $student_id])
            ->order('sc.create_time', 'desc')
            ->paginate($limit);

        if (!empty($data)) {
            foreach ($data as &$x) {
                $score_arr = $score_model
                    ->where(['shop_id' => $this->front_shop_id])
                    ->where(['delete_time' => 0])
                    ->where(['class_id' => $x['class_id']])
                    ->order('total_score', 'desc')
                    ->avg('total_score');
                $x['average'] = $score_arr;
            }
        }

        $this->assign('student_id',$student_id);
        $this->assign('data', $data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /*
     * 我的消息
     */

    public function mymssage()
    {
        $students = parent::cmf_get_current_student_id(); // TODO: Change the autogenerated stub
        $this->assign('students', $students);

        return $this->fetch();


    }

    /**
     *查看牛牛卡和奖学金
     */
    public function viewcard()
    {
        $student_id = $this->student();
        $p_id = cmf_get_current_user_id();
        $realname=Db::name('user')->where(['id'=>$p_id])->value('realname');
        $student_model=Db::name('student')->where(['id'=>$student_id])->find();

        $student_name=$student_model['name'];
        $code=$student_model['code'];


        $data = Db::name('award_card ac')->field(['ac.card_type', 'ac.id acid','ac.card_number', 'ac.award_money', 'ac.valid_date', 'ao.id aoid,ao.create_time aocreate_time'])
            ->join('award_student as', 'as.award_id=ac.id')
            ->join('award_order ao', 'ao.award_student_id=ac.id', $type = 'left')
            ->where(['as.student_id' => $student_id, 'as.delete_time' => 0])
            ->whereOr(['as.u_id' => $p_id])
            ->order('ac.id desc')
            ->paginate(10);
//    15053226646
        $data_record=Db::name('award_card_record')->alias('ar')->field('u.realname song_person1,uu.realname accept_person1,ar.*')
                ->join('user u','u.id=ar.song_person')
                ->join('user uu','uu.id=ar.accept_person')
                 ->where(['ar.accept_person'=>$p_id])
//                ->whereOr(['ar.accept_person'=>$p_id])
                ->order('ar.created_time desc')
                ->paginate(15);
        $this->assign('data', $data);
        $this->assign('code', $code);
        $this->assign('student_name', $student_name);

        $this->assign('realname', $realname);
        $this->assign('data_record', $data_record);
        $this->assign('student_id', $student_id);
        $this->assign('page', $data->render());
        $this->assign('page1', $data_record->render());
        return $this->fetch();
    }
    /**
     *后台用户绑定家长用户--只有牛牛卡
     */
    public function conform_card()
    {
        $param=$this->request->param();
        $student_id=$param['student_id']; //用户id，只是没有改
        $card_id = $param['card_id'];

        if(empty($card_id) || empty($student_id))
        {
            $this->error('没有此用户');
        }

        $p_id = cmf_get_current_user_id(); //当前用户
        $now_id=Db::name('award_student')->where('award_id',$card_id)->value('u_id');
        if($p_id!==$now_id)
        {
            $this->error('黑客失败');
        }

        $is_used = Db::name('award_order')->where(['u_id'=>$p_id,'award_student_id'=>$card_id])->find(); //如果使用过了，就不能转赠了对吧
        if(!empty($is_used))
        {
            return $this->error('此牛牛已经用过了，不能转赠了');
        }
        Db::startTrans();
        try{
            $id1=Db::name('award_student')->where('award_id',$card_id)->update(['is_used'=>1,'u_id'=>$student_id]);
            if($id1)
            {

                $user = cmf_get_current_user();
                $new_user = Db::name('user')->find($student_id);
                $old_user = Db::name('user')->find($p_id);

                $card_numer=Db::name('award_card')->where(['id'=>$card_id])->value('card_number');
                $p_realname=Db::name('user')->where(['id'=>$p_id])->value('realname');

                $recive_user=[];
                $recive_user[] = ['id' =>$student_id ];
                //前台发送消息
                $Message_model=new MessageModel();
                $data=[];
                $data['shop_id']=$this->front_shop_id;
                $data['send_uid']=$p_id;
                $data['subject']='转赠牛牛卡';
                $data['content']=$p_realname."把牛牛卡".$card_numer."转赠".$new_user['realname'];
                $data['type']=0;
                $data['create_time']=time();
                $Message_model->sendMsg($data,$recive_user);

                $recive_user1=[];
                $recive_user1[] = ['id' =>$p_id ];
                //前台发送消息
                $Message_model=new MessageModel();
                $data=[];
                $data['shop_id']=$this->front_shop_id;
                $data['send_uid']=$p_id;
                $data['subject']='转赠牛牛卡';
                $data['content']=$p_realname."把牛牛卡".$card_numer."转赠".$new_user['realname'];
                $data['type']=0;
                $data['create_time']=time();
                $Message_model->sendMsg($data,$recive_user1);

                //cmf_award_card_record
                $data1=[];
                $data1['shop_id']=$this->front_shop_id;
                $data1['song_person']=$p_id;
                $data1['accept_person']=$student_id;
                $data1['card_number']=$card_numer;
                $data1['created_time']=time();
                Db::name('award_card_record')->insert($data1);

                //后台操作记录记录日志
                $content = lang('CHANGE_CARD_USER',['name'=>$old_user['realname'],'date'=>date('Y-m-d H:i'),'oldname'=>$new_user['realname']]);
                do_log($content,1,'award_student',time(),$user['id']);
                Db::commit();

                $this->success('转赠成功');
            }
        }catch (Exception $e)
        {
            $this->error('转赠失败');
            Db::rollback();


        }

    }

    /**
     *查询家长用户
     */
    public function ajax_user()
    {
        $param=$this->request->param();
//        15053226646
        $mobile=$param['mobile'];
        $data=Db::name('user')->field(['id,realname'])->where(['mobile'=>$mobile])->find();
        if(empty($data))
        {
            return 0;
        }else{
            return json_encode($data);
        }

    }

    public function bing_ban()
    {
        $student_id=$this->student();
        $param=$this->request->param();
        $class_id=$param['class_id'];
        $old_class_id=$this->request->param('old_class_id',0);

        $pre_class_ids=$param['pre_class_ids'];
        //发现有没逗号
        $is_symbol=strpos($pre_class_ids,',');
        $pre_class=[];
        //前台占座
        if(!empty($old_class_id))
        {
            unset($_SESSION['old_class_id']);
            $_SESSION['old_class_id']=$old_class_id;
        }
        if($is_symbol)
        {
            $pre_class_ids=explode(',',$pre_class_ids);

            foreach($pre_class_ids as $k=>$v)
            {
                $name=Db::name('class')->where('id',$v)->value('name');
                $pre_class[$k]['name']=$name;
                $pre_class[$k]['id']=$v;

            }
        }else{
            $name=Db::name('class')->where('id',$pre_class_ids)->value('name');
            $pre_class[0]['name']=$name;
            $pre_class[0]['id']=$pre_class_ids;
        }
        $this->assign('student_id',$student_id);
         $this->assign('pre_class',$pre_class);

        return $this->fetch();
    }
    /*
   * 下载
   */
    public function  down()
    {


        $asset_id=$this->request->param('asset_id');
        $filepath=Db::name('asset')->where('id',$asset_id)->value('file_path');
        $filename=Db::name('asset')->where('id',$asset_id)->value('filename');

        $path=$_SERVER['DOCUMENT_ROOT']."/upload/".$filepath;
//         $path=$_SERVER['HTTP_HOST']."/upload/".$filepath;


        //实现下载这个功能代码
        header('content-disposition:attachment;filename='.$filename);

//        dump(__FILE__);
//        dump(basename(__FILE__));
//        exit();
//        header('content-disposition:attachment;filename='.basename(__FILE__));
        //要把下载文件里面的内容打印到这个页面
        readfile($path);
    }

}
